from machine import UART
import ujson

# 回调函数，收到服务器消息后会调用这个函数
def sub_cb(topic, msg):
    print(topic, msg)
    # ---- 添加 --------
    if topic.decode("utf-8") == "ledctl" and msg.decode("utf-8") == "on":
        led_pin.value(1)
    elif topic.decode("utf-8") == "ledctl" and msg.decode("utf-8") == "off":
        led_pin.value(0)
    # ---- 添加 --------

# 连接MQTT并订阅
def connect_and_subscribe():
  global client_id, mqtt_server, topic_sub
  # 建立一个MQTT客户端
  client = MQTTClient(client_id, mqtt_server)
  # 设置回调函数
  client.set_callback(sub_cb)
  # 建立连
  client.connect()
  # 监控ledctl这个通道，接收控制命令
  client.subscribe(topic_sub)
  print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))
  return client

# 重启并重新连接
def restart_and_reconnect():
  print('Failed to connect to MQTT broker. Reconnecting...')
  time.sleep(10)
  machine.reset()


try:
  client = connect_and_subscribe()
except OSError as e:
  restart_and_reconnect()

# uar串口通讯
uart=UART(2,115200)
uart.init(115200,bits=8,parity=None,stop=1) # 8N1

# 3. 创建LED对应Pin对象
led_pin = Pin(2, Pin.OUT)
    
dict = {}

while True:
    try:
        client.check_msg()
        if (time.time() - last_message) > message_interval:
            cmd=uart.readline()
            if cmd!=None:
                cmd=cmd.decode('utf-8','ignore')
                jsonResult = ujson.loads(cmd)
                #print(jsonResult)
                if jsonResult != None and jsonResult != '':
                    print(jsonResult['data'])
                    sn = jsonResult['data']['sn']
                    value = jsonResult['data']['value']
                    status = jsonResult['data']['status']
                    valueName = ''
                    # dht11
                    if sn == 1001 and status == True:
                        topic_pub='temperature,humidity'
                        valueName = 'temp,humi'
                    # distance
                    if sn == 1003 and status == True:
                        topic_pub='distance'
                        valueName = 'distance'
                    # fire
                    if sn == 1004 and status == True:
                        topic_pub = 'fire'
                        valueName = 'fire'
                    # voice
                    if sn == 1005 and status == True:
                        topic_pub = 'voice'
                        valueName = 'voice'
                    # game
                    if sn == 1006 and status == True:
                        topic_pub = 'game'
                        valueName = 'game'
                    # dht11 另外处理，有温度和湿度
                    if len(valueName.split(",")) >= 2 and len(topic_pub.split(",")) >= 2:
                        dict['sn'] = str(sn)
                        dict[valueName.split(',')[0]] = jsonResult['data']['value']['temp']
                        encoded = ujson.dumps(dict)
                        client.publish(topic_pub.split(',')[0].encode('utf-8'),encoded)
                        print("publish %s success! the content is: %s " % (topic_pub.split(',')[0],dict))
                        dict = {}
                        time.sleep(1)
                        
                        dict['sn'] = str(sn + 1)
                        dict[valueName.split(',')[1]] = jsonResult['data']['value']['humi']
                        encoded = ujson.dumps(dict)
                        client.publish(topic_pub.split(',')[1].encode('utf-8'),encoded)
                        print("publish %s success! the content is: %s " % (topic_pub.split(',')[1],dict))
                    else:
                        dict['sn'] = str(sn)
                        dict[valueName] = value
                        encoded = ujson.dumps(dict)
                        client.publish(topic_pub,encoded)
                        print("publish %s success! the content is: %s " % (topic_pub,dict))
                    last_message = time.time()
                    counter += 1
                    # 清空dict
                    dict = {}
    except OSError as e:
        restart_and_reconnect()
    except ValueError as e:
        pass

